/*
 * AdminCadastrar.java
 *
 * Created on 25/08/2009, 11:03:14
 * Copyright Jaime Jr
 */
package Adecot.Admin;

import Adecot.ApplicationBean1;
import Adecot.RequestBean1;
import Adecot.SessionBean1;
import Controller.AssociadoBO;
import Controller.Facade.IceDecorator;
import Controller.Facade.ValidaFacade;
import Controller.UsuarioBO;
import Model.Associado;
import Model.Usuario;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputSecret;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.ext.HtmlSelectOneRadio;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectedData;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectionItems;
import com.icesoft.faces.component.jsfcl.data.PopupBean;
import com.icesoft.faces.component.panellayout.PanelLayout;
import com.icesoft.faces.component.panelpopup.PanelPopup;
import com.icesoft.faces.component.selectinputtext.SelectInputText;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.xml.rpc.processor.modeler.j2ee.xml.string;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class Admin extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    private int __placeholder;
    private boolean parar;

   public boolean isParar() {
      return parar;
   }

   public void setParar(boolean parar) {
      this.parar = parar;
   }
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */

    
    private DefaultSelectionItems campoBuscaIncremental = new DefaultSelectionItems();

    public DefaultSelectionItems getCampoBuscaIncremental() {
        return campoBuscaIncremental;
    }

    public void setCampoBuscaIncremental(DefaultSelectionItems campoBuscaIncremental) {
        this.campoBuscaIncremental = campoBuscaIncremental;
    }

    private void _init() throws Exception {
    }
    private PopupBean painelPopupSair = new PopupBean();

    public PopupBean getPainelPopupSair() {
        return painelPopupSair;
    }

    public void setPainelPopupSair(PopupBean pb) {
        this.painelPopupSair = pb;
    }
    private PanelPopup painelSair = new PanelPopup();

    public PanelPopup getPainelSair() {
        return painelSair;
    }

    public void setPainelSair(PanelPopup pp) {
        this.painelSair = pp;
    }
    private PopupBean painelPopupConsultar = new PopupBean();

    public PopupBean getPainelPopupConsultar() {
        return painelPopupConsultar;
    }

    public void setPainelPopupConsultar(PopupBean pb) {
        this.painelPopupConsultar = pb;
    }
    private PanelPopup painelConsulta = new PanelPopup();

    public PanelPopup getPainelConsulta() {
        return painelConsulta;
    }

    public void setPainelConsulta(PanelPopup pp) {
        this.painelConsulta = pp;
    }
    private HtmlCommandButton botaoSairSim = new HtmlCommandButton();

    public HtmlCommandButton getBotaoSairSim() {
        return botaoSairSim;
    }

    public void setBotaoSairSim(HtmlCommandButton hcb) {
        this.botaoSairSim = hcb;
    }
    private HtmlCommandButton botaoSairNao = new HtmlCommandButton();

    public HtmlCommandButton getBotaoSairNao() {
        return botaoSairNao;
    }

    public void setBotaoSairNao(HtmlCommandButton hcb) {
        this.botaoSairNao = hcb;
    }
    private HtmlCommandButton botaoConsultaOk = new HtmlCommandButton();

    public HtmlCommandButton getBotaoConsultaOk() {
        return botaoConsultaOk;
    }

    public void setBotaoConsultaOk(HtmlCommandButton hcb) {
        this.botaoConsultaOk = hcb;
    }
    private HtmlCommandButton botaoConsultaCancelar = new HtmlCommandButton();

    public HtmlCommandButton getBotaoConsultaCancelar() {
        return botaoConsultaCancelar;
    }

    public void setBotaoConsultaCancelar(HtmlCommandButton hcb) {
        this.botaoConsultaCancelar = hcb;
    }
    private PopupBean painelPopupAviso = new PopupBean();

    public PopupBean getPainelPopupAviso() {
        return painelPopupAviso;
    }

    public void setPainelPopupAviso(PopupBean pb) {
        this.painelPopupAviso = pb;
    }
    private SelectInputText campoBuscaAdm = new SelectInputText();

    public SelectInputText getCampoBuscaAdm() {
        return campoBuscaAdm;
    }

    public void setCampoBuscaAdm(SelectInputText sit) {
        this.campoBuscaAdm = sit;
    }
    private HtmlOutputText msgAvisoResultado = new HtmlOutputText();

    public HtmlOutputText getMsgAvisoResultado() {
        return msgAvisoResultado;
    }

    public void setMsgAvisoResultado(HtmlOutputText hot) {
        this.msgAvisoResultado = hot;
    }
    private HtmlOutputText msgAvisoPergunta = new HtmlOutputText();

    public HtmlOutputText getMsgAvisoPergunta() {
        return msgAvisoPergunta;
    }

    public void setMsgAvisoPergunta(HtmlOutputText hot) {
        this.msgAvisoPergunta = hot;
    }
    private HtmlCommandButton botaoAvisoSim = new HtmlCommandButton();

    public HtmlCommandButton getBotaoAvisoSim() {
        return botaoAvisoSim;
    }

    public void setBotaoAvisoSim(HtmlCommandButton hcb) {
        this.botaoAvisoSim = hcb;
    }
    private HtmlCommandButton botaoAvisoNao = new HtmlCommandButton();

    public HtmlCommandButton getBotaoAvisoNao() {
        return botaoAvisoNao;
    }

    public void setBotaoAvisoNao(HtmlCommandButton hcb) {
        this.botaoAvisoNao = hcb;
    }
    private HtmlCommandButton botaoAlterar = new HtmlCommandButton();

    public HtmlCommandButton getBotaoAlterar() {
        return botaoAlterar;
    }

    public void setBotaoAlterar(HtmlCommandButton hcb) {
        this.botaoAlterar = hcb;
    }
    private PanelPopup painelAviso = new PanelPopup();

    public PanelPopup getPainelAviso() {
        return painelAviso;
    }

    public void setPainelAviso(PanelPopup pp) {
        this.painelAviso = pp;
    }
    private PopupBean painelPopupMensagem = new PopupBean();

    public PopupBean getPainelPopupMensagem() {
        return painelPopupMensagem;
    }

    public void setPainelPopupMensagem(PopupBean pb) {
        this.painelPopupMensagem = pb;
    }
    private HtmlOutputText msgMensagemResultado = new HtmlOutputText();

    public HtmlOutputText getMsgMensagemResultado() {
        return msgMensagemResultado;
    }

    public void setMsgMensagemResultado(HtmlOutputText hot) {
        this.msgMensagemResultado = hot;
    }
    private HtmlCommandButton botaoMensagemOk = new HtmlCommandButton();

    public HtmlCommandButton getBotaoMensagemOk() {
        return botaoMensagemOk;
    }

    public void setBotaoMensagemOk(HtmlCommandButton hcb) {
        this.botaoMensagemOk = hcb;
    }
    private PanelPopup painelMensagem = new PanelPopup();

    public PanelPopup getPainelMensagem() {
        return painelMensagem;
    }

    public void setPainelMensagem(PanelPopup pp) {
        this.painelMensagem = pp;
    }
    private HtmlCommandButton botaoNovo = new HtmlCommandButton();

    public HtmlCommandButton getBotaoNovo() {
        return botaoNovo;
    }

    public void setBotaoNovo(HtmlCommandButton hcb) {
        this.botaoNovo = hcb;
    }
    private HtmlCommandButton botaoConsultar = new HtmlCommandButton();

    public HtmlCommandButton getBotaoConsultar() {
        return botaoConsultar;
    }

    public void setBotaoConsultar(HtmlCommandButton hcb) {
        this.botaoConsultar = hcb;
    }
    private HtmlCommandButton botaoImprimir = new HtmlCommandButton();

    public HtmlCommandButton getBotaoImprimir() {
        return botaoImprimir;
    }

    public void setBotaoImprimir(HtmlCommandButton hcb) {
        this.botaoImprimir = hcb;
    }
    private HtmlCommandButton botaoLimpar = new HtmlCommandButton();

    public HtmlCommandButton getBotaoLimpar() {
        return botaoLimpar;
    }

    public void setBotaoLimpar(HtmlCommandButton hcb) {
        this.botaoLimpar = hcb;
    }
    private HtmlCommandButton botaoSair = new HtmlCommandButton();

    public HtmlCommandButton getBotaoSair() {
        return botaoSair;
    }

    public void setBotaoSair(HtmlCommandButton hcb) {
        this.botaoSair = hcb;
    }
    private HtmlCommandButton botaoCadastrar = new HtmlCommandButton();

    public HtmlCommandButton getBotaoCadastrar() {
        return botaoCadastrar;
    }

    public void setBotaoCadastrar(HtmlCommandButton hcb) {
        this.botaoCadastrar = hcb;
    }
    private HtmlInputText campoNome = new HtmlInputText();

    public HtmlInputText getCampoNome() {
        return campoNome;
    }

    public void setCampoNome(HtmlInputText hit) {
        this.campoNome = hit;
    }
    private HtmlInputText campoCpf = new HtmlInputText();

    public HtmlInputText getCampoCpf() {
        return campoCpf;
    }

    public void setCampoCpf(HtmlInputText hit) {
        this.campoCpf = hit;
    }
    private HtmlInputSecret campoSenha = new HtmlInputSecret();

    public HtmlInputSecret getCampoSenha() {
        return campoSenha;
    }

    public void setCampoSenha(HtmlInputSecret his) {
        this.campoSenha = his;
    }
    private HtmlInputText campoFraseSecreta = new HtmlInputText();

    public HtmlInputText getCampoFraseSecreta() {
        return campoFraseSecreta;
    }

    public void setCampoFraseSecreta(HtmlInputText hit) {
        this.campoFraseSecreta = hit;
    }
    private HtmlInputSecret campoConfirmaSenha = new HtmlInputSecret();

    public HtmlInputSecret getCampoConfirmaSenha() {
        return campoConfirmaSenha;
    }

    public void setCampoConfirmaSenha(HtmlInputSecret his) {
        this.campoConfirmaSenha = his;
    }
    private DefaultSelectedData associadoSimNao = new DefaultSelectedData();

    public DefaultSelectedData getAssociadoSimNao() {
        return associadoSimNao;
    }

    public void setAssociadoSimNao(DefaultSelectedData dsd) {
        this.associadoSimNao = dsd;
    }
    private DefaultSelectionItems opcoesAssociado = new DefaultSelectionItems();

    public DefaultSelectionItems getOpcoesAssociado() {
        return opcoesAssociado;
    }

    public void setOpcoesAssociado(DefaultSelectionItems dsi) {
        this.opcoesAssociado = dsi;
    }
    private HtmlSelectOneRadio radioAssociado = new HtmlSelectOneRadio();

    public HtmlSelectOneRadio getRadioAssociado() {
        return radioAssociado;
    }

    public void setRadioAssociado(HtmlSelectOneRadio hsor) {
        this.radioAssociado = hsor;
    }
    private DefaultSelectedData associadoSelecionado = new DefaultSelectedData();

    public DefaultSelectedData getAssociadoSelecionado() {
        return associadoSelecionado;
    }

    public void setAssociadoSelecionado(DefaultSelectedData dsd) {
        this.associadoSelecionado = dsd;
    }
    private DefaultSelectionItems associados = new DefaultSelectionItems();

    public DefaultSelectionItems getAssociados() {
        return associados;
    }

    public void setAssociados(DefaultSelectionItems dsi) {
        this.associados = dsi;
    }
    private HtmlSelectOneMenu comboAssociado = new HtmlSelectOneMenu();

    public HtmlSelectOneMenu getComboAssociado() {
        return comboAssociado;
    }

    public void setComboAssociado(HtmlSelectOneMenu hsom) {
        this.comboAssociado = hsom;
    }
    private PanelLayout painelAssociado = new PanelLayout();

    public PanelLayout getPainelAssociado() {
        return painelAssociado;
    }

    public void setPainelAssociado(PanelLayout pl) {
        this.painelAssociado = pl;
    }
    private PanelLayout painelNome = new PanelLayout();

    public PanelLayout getPainelNome() {
        return painelNome;
    }

    public void setPainelNome(PanelLayout pl) {
        this.painelNome = pl;
    }
    private DefaultSelectedData nivelMarcado = new DefaultSelectedData();

    public DefaultSelectedData getNivelMarcado() {
        return nivelMarcado;
    }

    public void setNivelMarcado(DefaultSelectedData dsd) {
        this.nivelMarcado = dsd;
    }
    private DefaultSelectionItems niveis = new DefaultSelectionItems();

    public DefaultSelectionItems getNiveis() {
        return niveis;
    }

    public void setNiveis(DefaultSelectionItems dsi) {
        this.niveis = dsi;
    }
    private HtmlSelectOneRadio radioNiveis = new HtmlSelectOneRadio();

    public HtmlSelectOneRadio getRadioNiveis() {
        return radioNiveis;
    }

    public void setRadioNiveis(HtmlSelectOneRadio hsor) {
        this.radioNiveis = hsor;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public Admin() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     *
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("AdminCadastrar Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }        
        painelSair.setRendered(false);
        painelConsulta.setRendered(false);
        painelAviso.setRendered(false);
        painelMensagem.setRendered(false);

        botaoAlterar.setDisabled(true);
        

        painelAssociado.setRendered(false);
        painelNome.setRendered(false);

        opcoesAssociado.clear();
        opcoesAssociado.add(new SelectItem("Sim", "Sim"));
        opcoesAssociado.add(new SelectItem("Não", "Não"));

        niveis.clear();
        niveis.add(new SelectItem("Usuário", "Usuário"));
        niveis.add(new SelectItem("Administrador", "Administrador"));


        //montando combo com a Associado
        associados.clear();
        setAssociados(new IceDecorator(AssociadoBO.class).montaCombo());        
        SelectItem valor = (SelectItem) associados.get(0);
    //    comboAssociado.setValue(valor.getValue());
    //comboAssociado.setValue(new Integer(0));

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    //ação dos botões do painel de opções
    public String botaoConsultar_action() {
        limparCampos();
        painelConsulta.setRendered(true);
        return null;
    }

    public String botaoSair_action() {
        painelSair.setRendered(true);
        return null;
    }

    public String botaoCadastrar_action() {
        try {
            Usuario administrador = (Usuario) getBean("Usuario");
            System.out.println(radioAssociado.getValue().toString());
            if (radioAssociado.getValue().toString().equals("Sim")) {
                Associado associado = (Associado) new IceDecorator(AssociadoBO.class).retornaObjetoCodigo("codAssociado", Integer.parseInt(comboAssociado.getValue().toString()));

                administrador.setNome(associado.getNome());
                administrador.setAssociado(associado);
                administrador.setCliente(true);

            }
            else
                administrador.setCliente(false);

            new IceDecorator(UsuarioBO.class).salvar(administrador);
            msgMensagemResultado.setValue("Operação Efetuada Com Sucesso!");
            painelMensagem.setRendered(true);
            limparCampos();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getCause());
            msgMensagemResultado.setValue("Erro Ao Efetuar Operação");
            //msgMensagemOperacao.setValue("Verificar :" + e.getMessage());
            painelMensagem.setRendered(true);
        }
        return null;
    }

    public String botaoNovo_action() {
        habilitarCampos();
        limparCampos();
        return null;
    }

    public String botaoLimpar_action() {
        habilitarCampos();
        limparCampos();
        return null;
    }

    public String botaoAlterar_action() {
        setParar(true);
        habilitarCampos();
        return null;
    }


    //ação dos botões dos pop ups
    public String botaoSairSim_action() {

        return "menu";
    }

    public String botaoSairNao_action() {
        painelSair.setRendered(false);
        return null;
    }

    public String botaoConsultaCancelar_action() {
        painelConsulta.setRendered(false);
        return null;
    }

    public String botaoConsultaOk_action() {

        try {
            Usuario user = (Usuario) new IceDecorator(UsuarioBO.class).retornaObjeto("nome", campoBuscaAdm.getValue().toString());            
            limparCampos();

            if(user.getCliente().booleanValue() == true){
                setBean("Usuario", user);
                painelAssociado.setRendered(true);
                painelNome.setRendered(false);
                comboAssociado.setValue(user.getAssociado().getCodAssociado());
                radioAssociado.setValue("Sim");
                radioAssociado.setReadonly(false);
                radioNiveis.setReadonly(false);
            }
            else if(user.getCliente().booleanValue() == false) {
                  setBean("Usuario", user);
                  painelNome.setRendered(true);
                  painelAssociado.setRendered(false);
                  radioAssociado.setValue("Não");
                  radioAssociado.setReadonly(true);
                  radioNiveis.setReadonly(true);
           }
            
            desabilitarCampos();
            painelConsulta.setRendered(false);
            botaoAlterar.setDisabled(false);

        } catch (Exception e) {
            painelAviso.setRendered(true);
            msgAvisoResultado.setValue("Não houve resultado para esta consulta!");
        }
        return null;
    }

    public String botaoAvisoSim_action() {
        painelAviso.setRendered(false);
        return null;
    }

    public String botaoAvisoNao_action() {
        painelAviso.setRendered(false);
        painelConsulta.setRendered(false);
        return null;
    }

    public String botaoMensagemOk_action() {
        painelMensagem.setRendered(false);
        //msgMensagemOperacao.setValue("");
        return null;
    }


    //métodos para uso dos botões
    public void limparCampos() {
        FacesContext.getCurrentInstance().getExternalContext().getRequestMap().clear();

        radioAssociado.resetValue();
        radioNiveis.resetValue();
        comboAssociado.resetValue();
        campoNome.resetValue();
        campoCpf.resetValue();
        campoSenha.resetValue();
        campoConfirmaSenha.resetValue();
        campoFraseSecreta.resetValue();
        campoBuscaAdm.resetValue();
        setParar(false);
        habilitarCampos();
    }

    public void habilitarCampos() {

        radioAssociado.setReadonly(false);
        radioNiveis.setReadonly(false);
        comboAssociado.setDisabled(false);
        campoNome.setDisabled(false);
        campoCpf.setDisabled(false);
        campoSenha.setDisabled(false);
        campoConfirmaSenha.setDisabled(false);
        campoFraseSecreta.setDisabled(false);
    }

    public void desabilitarCampos() {

        radioAssociado.setReadonly(true);
        radioNiveis.setReadonly(true);
        comboAssociado.setDisabled(true);
        campoNome.setDisabled(true);
        campoCpf.setDisabled(true);
        campoSenha.setDisabled(true);
        campoConfirmaSenha.setDisabled(true);
        campoFraseSecreta.setDisabled(true);
    }

    public void validaConfirmaSenha(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        FacesMessage msg = new FacesMessage();
        if (!value.toString().equals(campoSenha.getValue().toString())) {
            msg.setSummary("*");
            msg.setDetail("Confirmação de senha não confere");
            throw new ValidatorException(msg);
        }
    }

    //ação dos campos
   /*método para consulta incremental que muda o valor da lista incremental a partir do valor digitado*/
    public void campoBuscaAdm_processValueChange(ValueChangeEvent vce) {
        try {
            this.setCampoBuscaIncremental(new IceDecorator(UsuarioBO.class).consultaIncremental("nome", campoBuscaAdm.getValue().toString()));
        } catch (Exception e) {
        }
    }

    public void radioAssociado_processValueChange(ValueChangeEvent vce) {
        if (radioAssociado.getValue().equals("Não")) {
            painelNome.setRendered(true);
            painelAssociado.setRendered(false);
            campoCpf.setReadonly(false);
            campoCpf.setValue("");
        }
        else{
            painelNome.setRendered(false);
            painelAssociado.setRendered(true);
            campoCpf.setReadonly(true);
        }
    }

    public void comboAssociado_processValueChange(ValueChangeEvent vce) throws Exception {
        Associado associado = (Associado) new IceDecorator(AssociadoBO.class).retornaObjetoCodigo("codAssociado",
                Integer.parseInt(comboAssociado.getValue().toString()));
        campoCpf.setValue(associado.getCpf());
        
    }

    public void comboAssociado_validate(FacesContext context, UIComponent component, Object value) {
        new ValidaFacade().validateCampoUnico(context, component, Integer.parseInt(value.toString()), UsuarioBO.class, parar);
    }
}

